package com.fingard.dsp.bank.directbank.cib01;

import com.fingard.FGBiz;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.ITransaction;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7515TodayTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7516HisTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.RetAtsTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.detail.RetAtsTransDetail;
import com.fingard.text.StringHelper;
import com.fingard.util.DateHelper;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.Date;
@Component("CIB01Transaction")
public class CIB01Transaction extends CIB01Base implements ITransaction {
    public RetAtsTrans d_7516_HisTrans(Req7516HisTrans p_req7516) throws Exception {
        RetAtsTrans retAts = new RetAtsTrans(p_req7516.reqHeader);
        boolean isNeedSubActTran = getBankConfig().getValueAsBool("isNeedSubActTran");
        if (isNeedSubActTran) {
            queryHisTransByBALNTRADEINQUIRYTRNRQ(p_req7516, retAts);
        } else {
            queryHisTransBySCUSTSTMTRQ(p_req7516, retAts);
        }


        retAts.writeEnd();
        return retAts;
    }

    //历史明细中会返回
    private void queryHisTransByBALNTRADEINQUIRYTRNRQ(Req7516HisTrans p_req7516, RetAtsTrans retAts) throws Exception {
        String tmpRespCode = "";
        String tmpRespInfo = "";
        retAts.writeStart();
        try {
            Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(p_req7516.getDateFrom());

            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(p_req7516.getDateTo());

            int tmpIntDateFrom = 0;
            int tmpIntDateTo = 0;
            boolean isSubAct = false;
            String queryAct;
            if (StringHelper.hasAnyChar(p_req7516.higherLevelAct) && !p_req7516.actNum.equals(p_req7516.higherLevelAct)) {
                isSubAct = true;
                queryAct = p_req7516.higherLevelAct;
            } else {
                isSubAct = false;
                queryAct = p_req7516.actNum;
            }
            //按自然月循环查询
            while (tmpIntDateFrom <= tmpIntDateTo && tmpRespCode.length() == 0) {
                Calendar tmpClndrStepTo = Calendar.getInstance();
                tmpClndrStepTo.setTime(tmpCalendarFrom.getTime());
                //判断是否跨月
                if (DateHelper.compareMonth(tmpCalendarFrom, tmpCalendarTo) == -1) {
                    //跨月则设置为月末
                    tmpClndrStepTo.set(Calendar.DAY_OF_MONTH, tmpClndrStepTo.getActualMaximum(Calendar.DAY_OF_MONTH));
                } else {
                    tmpClndrStepTo.setTime(tmpCalendarTo.getTime());
                }
                boolean queryFlag = true;
                int pageIndex = 0;
                while (queryFlag) {
                    pageIndex++;
                    XmlTextWriter xmlWriter = new XmlTextWriter();
                    writeCommonHeader(xmlWriter);
                    xmlWriter.writeStartElement("SECURITIES_MSGSRQV1");
                    xmlWriter.writeStartElement(CIB01TransType.Q7516_2);
                    xmlWriter.writeElementString("TRNUID", getQryTransID());//p_req7516.reqHeader.transSeqID);
                    xmlWriter.writeStartElement("RQBODY");
                    xmlWriter.writeStartElement("ACCTFROM");
                    xmlWriter.writeElementString("ACCTID", queryAct);
                    xmlWriter.writeEndElement();
                    xmlWriter.writeStartElement("INCTRAN");

                    xmlWriter.writeElementString("DTSTART", Format.Date10Format.format(tmpCalendarFrom.getTime()));
                    xmlWriter.writeElementString("DTEND", Format.Date10Format.format(tmpClndrStepTo.getTime()));
                    xmlWriter.writeElementString("PAGE", pageIndex + "");
                    xmlWriter.writeEndDocument();
                    String xmlSend = writeContentLength(xmlWriter);

                    String[] tmpStrRet = sendToBank(xmlSend);
                    XmlTextReader tmpBkReader;

                    String returnXml = tmpStrRet[1].substring(tmpStrRet[1].indexOf("<FOX>"), tmpStrRet[1].length());
                    if (tmpStrRet[0].length() == 0) {
                        StringBuilder tmpSbMsg = new StringBuilder();
                        tmpBkReader = loadBankRespXmlReader(returnXml, tmpSbMsg);
                        if (tmpBkReader != null) {
                            String retCode = tmpBkReader.getFirstText("/FOX/SECURITIES_MSGSRSV1/BALNTRADEINQUIRYTRNRS/STATUS/CODE");
                            String retMsg = tmpBkReader.getFirstText("/FOX/SECURITIES_MSGSRSV1/SCUSTSTMTTRNRS/STATUS/MESSAGE");
                            if (retCode.equals("0")) {
                                if (pageIndex <= 1) {
                                    if (tmpBkReader.countElement("/FOX/SECURITIES_MSGSRSV1/BALNTRADEINQUIRYTRNRS/RSBODY/CONTENT") < 1)//返回0表示无记录
                                    {
//                                        tmpRespCode = "-1";
                                        tmpRespInfo = "银行返回记录为空！";
                                        break;
                                    }
                                }
                                queryFlag = returnXml.contains("RSBODY MORE=\"Y\"");
                                while (tmpBkReader.read("/FOX/SECURITIES_MSGSRSV1/BALNTRADEINQUIRYTRNRS/RSBODY/CONTENT")) {
                                    XElement tmpRetNode = tmpBkReader.readedXElement;
                                    String subActNum = tmpRetNode.getSingleText("SUBACCT");
                                    if (isSubAct && StringHelper.hasAnyChar(subActNum) && p_req7516.actNum.equals(subActNum)) {

                                    } else if (!isSubAct && (StringHelper.isNullOrEmpty(subActNum) || "999999".equals(subActNum))) {

                                    } else {
                                        continue;
                                    }
                                    RetAtsTransDetail tmpRetDetail = new RetAtsTransDetail();
                                    tmpRetDetail.actNum = p_req7516.actNum;
                                    String dealDate = tmpRetNode.getSingleText("DTACCT").substring(0, 10);
                                    String dealTime = tmpRetNode.getSingleText("DTACCT").replaceAll("T", " ");
                                    tmpRetDetail.tranDate = dealDate;//格式yyyy-MM-dd
                                    tmpRetDetail.valueDate = dealDate;//格式yyyy-MM-dd
                                    tmpRetDetail.tranTime = dealTime;//格式"yyyy-MM-dd HH:mm:ss"
                                    // #start 提取摘要、备注，摘要和备注中有一个字段含有对账码，通过提取方法获取对账码
                                    tmpRetDetail.comment = tmpRetNode.getSingleTextNotNull("MEMO").trim();
                                    tmpRetDetail.usage = tmpRetNode.getSingleTextNotNull("MEMO").trim();
//                                    tmpRetDetail.abstr = pickupAbstr(tmpRetDetail.comment);//对账码写在备注字段的最前面，和备注摘要用|号分割
                                    tmpRetDetail.recAccNum = tmpRetNode.getSingleTextNotNull("CORRELATE_ACCTID").trim();
                                    tmpRetDetail.recAccName = tmpRetNode.getSingleTextNotNull("CORRELATE_NAME").trim();
                                    tmpRetDetail.recAccBank = tmpRetNode.getSingleTextNotNull("CORRELATE_BANKNAME").trim();
                                    String memo = tmpRetNode.getSingleTextNotNull("MEMO").trim();
                                    tmpRetDetail.abstr = memo.substring(memo.indexOf("+") + 1, memo.length());
                                    tmpRetDetail.payCode = memo.substring(0, memo.lastIndexOf("+"));

                                    if (isSubAct) {
                                        tmpRetDetail.accBal = "0.00";
                                    } else {
                                        tmpRetDetail.accBal = tmpRetNode.getSingleText("BALAMT");
                                    }
                                    // #end
                                    // #start "发生额、余额、借贷标志 0-借 1-贷"
                                    String dealMoney = tmpRetNode.getSingleText("TRNAMT");//交易金额
                                    String loanSign = tmpRetNode.getSingleText("TRNTYPE");//借贷标志
                                    if (loanSign.equals("DEBIT")) {
                                        if (dealMoney.indexOf("-") < 0) {//借正，正常业务
                                            tmpRetDetail.tranAmt = dealMoney;
                                            tmpRetDetail.cdFlag = "1";
                                        } else {//借负，银行退票,表示收入
                                            tmpRetDetail.tranAmt = dealMoney.replace("-", "");
                                            tmpRetDetail.cdFlag = "2";//借贷表示置为贷，表示收入
                                        }
                                    } else {
                                        if (dealMoney.indexOf("-") < 0) {//贷正，正常业务
                                            tmpRetDetail.tranAmt = dealMoney;
                                            tmpRetDetail.cdFlag = "2";
                                        } else {//贷负，目前应该没有这种业务，按照正常的程序逻辑做一下处理
                                            tmpRetDetail.tranAmt = dealMoney.replace("-", "");
                                            tmpRetDetail.cdFlag = "1";//借贷表示置为借，表示支出
                                        }
                                    }
                                    tmpRetDetail.originator = tmpBkReader.readedXElement.getSingleTextNotNull("ATTACHINFO");
                                    tmpRetDetail.bnkSeqNo = tmpBkReader.readedXElement.getSingleTextNotNull("ATTACHINFO");
                                    // #end
                                    nodeAnalysic(tmpBkReader.readedXElement, tmpRetDetail, getCharset());
                                    retAts.writeRetDetail(tmpRetDetail);
                                }
                            } else {
                                //  "查询失败"
                                tmpRespCode = "-1";
                                tmpRespInfo = "查询明细失败，银行返回信息：" + retMsg;
                                queryFlag = false;
                            }
                        } else {
                            tmpRespCode = "-1";
                            tmpRespInfo = tmpSbMsg.toString();
                        }
                    } else {
                        tmpRespCode = "-1";
                        tmpRespInfo = tmpStrRet[1];
                    }
                }
                tmpCalendarFrom = tmpClndrStepTo;
                tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);
                tmpIntDateFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
                tmpIntDateTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
            }
        } catch (Exception ex) {
            FGBiz.limitMsg.exception(reqHeader.bankCode, ex);
            tmpRespCode = "-1";
            tmpRespInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }
        if ("-1".equals(tmpRespCode)) {
            retAts = new RetAtsTrans(p_req7516.reqHeader);
            retAts.writeStart();//写返回ATS的统一头部信息
            retAts.writeRespCode(tmpRespCode);
            retAts.writeRespInfo(tmpRespInfo);
        } else if (retAts.getWrittenRdCount() == 0) {
            retAts.writeRespCode("0");
            retAts.writeRespInfo("交易为空");
        }
    }

    private void queryHisTransBySCUSTSTMTRQ(Req7516HisTrans p_req7516, RetAtsTrans retAts) throws Exception {
        String tmpRespCode = "";
        String tmpRespInfo = "";
        retAts.writeStart();
        try {
            Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(p_req7516.getDateFrom());

            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(p_req7516.getDateTo());

            int tmpIntDateFrom = 0;
            int tmpIntDateTo = 0;
            //按自然月循环查询
            while (tmpIntDateFrom <= tmpIntDateTo && tmpRespCode.length() == 0) {
                Calendar tmpClndrStepTo = Calendar.getInstance();
                tmpClndrStepTo.setTime(tmpCalendarFrom.getTime());
                //判断是否跨月
                if (DateHelper.compareMonth(tmpCalendarFrom, tmpCalendarTo) == -1) {
                    //跨月则设置为月末
                    tmpClndrStepTo.set(Calendar.DAY_OF_MONTH, tmpClndrStepTo.getActualMaximum(Calendar.DAY_OF_MONTH));
                } else {
                    tmpClndrStepTo.setTime(tmpCalendarTo.getTime());
                }
                boolean queryFlag = true;
                int pageIndex = 0;
                while (queryFlag) {
                    pageIndex++;
                    XmlTextWriter xmlWriter = new XmlTextWriter();
                    writeCommonHeader(xmlWriter);
                    xmlWriter.writeStartElement("SECURITIES_MSGSRQV1");
                    xmlWriter.writeStartElement(CIB01TransType.Q7516);
                    xmlWriter.writeElementString("TRNUID", getQryTransID());//p_req7516.reqHeader.transSeqID);
                    xmlWriter.writeStartElement("SCUSTSTMTRQ");
                    xmlWriter.writeStartElement("ACCTFROM");
                    xmlWriter.writeElementString("ACCTID", p_req7516.actNum);
                    xmlWriter.writeEndElement();
                    xmlWriter.writeStartElement("INCTRAN");

                    xmlWriter.writeElementString("DTSTART", Format.Date10Format.format(tmpCalendarFrom.getTime()));
                    xmlWriter.writeElementString("DTEND", Format.Date10Format.format(tmpClndrStepTo.getTime()));
                    xmlWriter.writeElementString("PAGE", pageIndex + "");
                    xmlWriter.writeEndDocument();
                    String xmlSend = writeContentLength(xmlWriter);

                    String[] tmpStrRet = sendToBank(xmlSend);
                    XmlTextReader tmpBkReader;

                    String returnXml = tmpStrRet[1].substring(tmpStrRet[1].indexOf("<FOX>"), tmpStrRet[1].length());
                    if (tmpStrRet[0].length() == 0) {
                        StringBuilder tmpSbMsg = new StringBuilder();
                        tmpBkReader = loadBankRespXmlReader(returnXml, tmpSbMsg);
                        if (tmpBkReader != null) {
                            String retCode = tmpBkReader.getFirstText("/FOX/SECURITIES_MSGSRSV1/SCUSTSTMTTRNRS/STATUS/CODE");
                            String retServerity = tmpBkReader.getFirstText("/FOX/SECURITIES_MSGSRSV1/SCUSTSTMTTRNRS/STATUS/SEVERITY");
                            if (retCode.equals("0")) {
                                if (pageIndex <= 1) {
                                    if (tmpBkReader.countElement("/FOX/SECURITIES_MSGSRSV1/SCUSTSTMTTRNRS/SCUSTSTMTRS/TRANLIST/STMTTRN") < 1)//返回0表示无记录
                                    {
//                                        tmpRespCode = "-1";
                                        tmpRespInfo = "银行返回记录为空！";
                                        break;
                                    }
                                }
                                queryFlag = returnXml.contains("TRANLIST MORE=\"Y\"");
                                while (tmpBkReader.read("/FOX/SECURITIES_MSGSRSV1/SCUSTSTMTTRNRS/SCUSTSTMTRS/TRANLIST/STMTTRN")) {
                                    RetAtsTransDetail tmpRetDetail = new RetAtsTransDetail();
                                    tmpRetDetail.actNum = p_req7516.actNum;
                                    XElement tmpRetNode = tmpBkReader.readedXElement;
                                    String dealDate = tmpRetNode.getSingleText("DTACCT").substring(0, 10);
                                    String dealTime = tmpRetNode.getSingleText("DTACCT").replaceAll("T", " ");
                                    tmpRetDetail.tranDate = dealDate;//格式yyyy-MM-dd
                                    tmpRetDetail.valueDate = dealDate;//格式yyyy-MM-dd
                                    tmpRetDetail.tranTime = dealTime;//格式"yyyy-MM-dd HH:mm:ss"
                                    // #start 提取摘要、备注，摘要和备注中有一个字段含有对账码，通过提取方法获取对账码-----范天星/2020/01/19
                                    String memo = tmpRetNode.getSingleTextNotNull("MEMO").trim();
                                    if (memo.contains("+")){
                                        tmpRetDetail.comment = memo.substring(0, memo.lastIndexOf("+"));
                                        tmpRetDetail.usage = memo.substring(0, memo.lastIndexOf("+"));
                                        tmpRetDetail.abstr = memo.substring(memo.lastIndexOf("+") + 1, memo.length());
                                    } else {
                                        tmpRetDetail.comment = memo;
                                        tmpRetDetail.usage = memo;
                                        tmpRetDetail.abstr = "";
                                    }
//                                    tmpRetDetail.abstr = pickupAbstr(tmpRetDetail.comment);//对账码写在备注字段的最前面，和备注摘要用|号分割
                                    tmpRetDetail.recAccNum = tmpRetNode.getSingleTextNotNull("CORRELATE_ACCTID").trim();
                                    tmpRetDetail.recAccName = tmpRetNode.getSingleTextNotNull("CORRELATE_NAME").trim();
                                    tmpRetDetail.recAccBank = tmpRetNode.getSingleTextNotNull("CORRELATE_BANKNAME").trim();
                                    tmpRetDetail.payCode = tmpRetNode.getSingleTextNotNull("MEMO").trim();
                                    tmpRetDetail.accBal = tmpRetNode.getSingleText("BALAMT");
                                    // #end
                                    // #start "发生额、余额、借贷标志 0-借 1-贷"
                                    String dealMoney = tmpRetNode.getSingleText("TRNAMT");//交易金额
                                    String loanSign = tmpRetNode.getSingleText("TRNTYPE");//借贷标志
                                    if (loanSign.equals("DEBIT")) {
                                        if (dealMoney.indexOf("-") < 0) {//借正，正常业务
                                            tmpRetDetail.tranAmt = dealMoney;
                                            tmpRetDetail.cdFlag = "1";
                                        } else {//借负，银行退票,表示收入
                                            tmpRetDetail.tranAmt = dealMoney.replace("-", "");
                                            tmpRetDetail.cdFlag = "2";//借贷表示置为贷，表示收入
                                        }
                                    } else {
                                        if (dealMoney.indexOf("-") < 0) {//贷正，正常业务
                                            tmpRetDetail.tranAmt = dealMoney;
                                            tmpRetDetail.cdFlag = "2";
                                        } else {//贷负，目前应该没有这种业务，按照正常的程序逻辑做一下处理
                                            tmpRetDetail.tranAmt = dealMoney.replace("-", "");
                                            tmpRetDetail.cdFlag = "1";//借贷表示置为借，表示支出
                                        }
                                    }
                                    tmpRetDetail.originator = tmpBkReader.readedXElement.getSingleTextNotNull("ATTACHINFO");
                                    tmpRetDetail.bnkSeqNo = tmpBkReader.readedXElement.getSingleTextNotNull("ATTACHINFO");
                                    // #end
                                    nodeAnalysic(tmpBkReader.readedXElement, tmpRetDetail, getCharset());
                                    retAts.writeRetDetail(tmpRetDetail);
                                }
                                //当没有明细记录时的返回结果
                            } else if ("6421".equals(retCode) && "INFO".equals(retServerity)) {
                                queryFlag = false;
                            } else {
                                //  "查询失败"
                                tmpRespCode = "-1";
                                tmpRespInfo = "查询明细失败，银行返回信息：" + tmpBkReader.getFirstText("/FOX/SECURITIES_MSGSRSV1/SCUSTSTMTTRNRS/STATUS/MESSAGE");
                                queryFlag = false;
                            }
                        } else {
                            tmpRespCode = "-1";
                            tmpRespInfo = tmpSbMsg.toString();
                        }
                    } else {
                        tmpRespCode = "-1";
                        tmpRespInfo = tmpStrRet[1];
                    }
                }
                tmpCalendarFrom = tmpClndrStepTo;
                tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);
                tmpIntDateFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
                tmpIntDateTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
            }
        } catch (Exception ex) {
            FGBiz.limitMsg.exception(reqHeader.bankCode, ex);
            tmpRespCode = "-1";
            tmpRespInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }
        if ("-1".equals(tmpRespCode)) {
            retAts = new RetAtsTrans(p_req7516.reqHeader);
            retAts.writeStart();//写返回ATS的统一头部信息
            retAts.writeRespCode(tmpRespCode);
            retAts.writeRespInfo(tmpRespInfo);
        } else if (retAts.getWrittenRdCount() == 0) {
            retAts.writeRespCode("0");
            retAts.writeRespInfo("交易为空");
        }
    }

    public RetAtsTrans d_7515_TodayTrans(Req7515TodayTrans p_req7515) throws Exception {
        Req7516HisTrans tmpReq7516 = new Req7516HisTrans(p_req7515.reqHeader);
        tmpReq7516.actArea = p_req7515.actArea;
        tmpReq7516.actCur = p_req7515.actCur;
        tmpReq7516.actNum = p_req7515.actNum;
        tmpReq7516.higherLevelAct = p_req7515.higherLevelAct;
        String tmpStrToday = Format.Date8Format.format(new Date());
        tmpReq7516.dateFrom = tmpStrToday;//设置开始时间和结束时间都为当天
        tmpReq7516.dateTo = tmpStrToday;
        return d_7516_HisTrans(tmpReq7516);
    }
}
